#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目配置
PROJECT_NAME="lab-web"
COMPOSE_FILE="docker-compose.yml"
BACKUP_DIR="./backups"

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_blue() {
    echo -e "${BLUE}[DEPLOY]${NC} $1"
}

# 检查Docker是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        exit 1
    fi

    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose未安装，请先安装Docker Compose"
        exit 1
    fi

    log_info "Docker环境检查通过"
}

# 创建必要目录
create_directories() {
    log_info "创建必要目录..."
    mkdir -p data uploads public/uploads logs logs/nginx ssl $BACKUP_DIR
    chmod 755 data uploads public/uploads logs
    log_info "目录创建完成"
}

# 备份数据
backup_data() {
    if [ ! -d "data" ]; then
        log_warn "没有找到数据目录，跳过备份"
        return
    fi

    local backup_name="backup_$(date +%Y%m%d_%H%M%S)"
    log_info "创建数据备份: $backup_name"
    
    mkdir -p $BACKUP_DIR/$backup_name
    cp -r data $BACKUP_DIR/$backup_name/
    cp -r uploads $BACKUP_DIR/$backup_name/ 2>/dev/null || true
    
    # 保留最近5个备份
    cd $BACKUP_DIR
    ls -t | tail -n +6 | xargs -r rm -rf
    cd ..
    
    log_info "备份完成: $BACKUP_DIR/$backup_name"
}

# 构建镜像
build_image() {
    log_blue "构建Docker镜像..."
    docker-compose -f $COMPOSE_FILE build --no-cache
    if [ $? -eq 0 ]; then
        log_info "镜像构建成功"
    else
        log_error "镜像构建失败"
        exit 1
    fi
}

# 启动服务
start_services() {
    log_blue "启动服务..."
    docker-compose -f $COMPOSE_FILE up -d
    if [ $? -eq 0 ]; then
        log_info "服务启动成功"
    else
        log_error "服务启动失败"
        exit 1
    fi
}

# 停止服务
stop_services() {
    log_blue "停止服务..."
    docker-compose -f $COMPOSE_FILE down
    log_info "服务已停止"
}

# 重启服务
restart_services() {
    log_blue "重启服务..."
    docker-compose -f $COMPOSE_FILE restart
    log_info "服务重启完成"
}

# 查看服务状态
show_status() {
    log_blue "服务状态:"
    docker-compose -f $COMPOSE_FILE ps
    
    echo ""
    log_blue "容器日志:"
    docker-compose -f $COMPOSE_FILE logs --tail=20
}

# 查看日志
show_logs() {
    local service=${1:-lab-web}
    log_blue "查看 $service 服务日志:"
    docker-compose -f $COMPOSE_FILE logs -f $service
}

# 清理资源
cleanup() {
    log_blue "清理Docker资源..."
    docker system prune -f
    docker volume prune -f
    log_info "清理完成"
}

# 健康检查
health_check() {
    log_blue "执行健康检查..."
    
    # 等待服务启动
    sleep 10
    
    # 检查容器状态
    if docker-compose -f $COMPOSE_FILE ps | grep -q "Up"; then
        log_info "容器运行正常"
    else
        log_error "容器未正常运行"
        return 1
    fi
    
    # 检查HTTP响应
    if curl -f http://localhost:3000/ >/dev/null 2>&1; then
        log_info "HTTP服务响应正常"
    else
        log_warn "HTTP服务无响应，请检查服务状态"
    fi
}

# 完整部署流程
full_deploy() {
    log_blue "开始完整部署流程..."
    
    check_docker
    create_directories
    backup_data
    build_image
    stop_services
    start_services
    health_check
    
    log_info "部署完成！"
    log_info "访问地址: http://localhost:3000"
    log_info "管理后台: http://localhost:3000/admin"
}

# 快速更新
quick_update() {
    log_blue "开始快速更新..."
    
    backup_data
    build_image
    restart_services
    health_check
    
    log_info "更新完成！"
}

# 显示帮助
show_help() {
    echo "使用方法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  deploy     完整部署（首次部署推荐）"
    echo "  update     快速更新（保持数据）"
    echo "  start      启动服务"
    echo "  stop       停止服务"
    echo "  restart    重启服务"
    echo "  status     查看服务状态"
    echo "  logs       查看日志 [service]"
    echo "  backup     备份数据"
    echo "  cleanup    清理Docker资源"
    echo "  health     健康检查"
    echo "  help       显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 deploy          # 首次完整部署"
    echo "  $0 update          # 更新应用"
    echo "  $0 logs nginx      # 查看nginx日志"
}

# 主程序
main() {
    case "${1:-help}" in
        "deploy")
            full_deploy
            ;;
        "update")
            quick_update
            ;;
        "start")
            start_services
            ;;
        "stop")
            stop_services
            ;;
        "restart")
            restart_services
            ;;
        "status")
            show_status
            ;;
        "logs")
            show_logs $2
            ;;
        "backup")
            backup_data
            ;;
        "cleanup")
            cleanup
            ;;
        "health")
            health_check
            ;;
        "help"|*)
            show_help
            ;;
    esac
}

main "$@"